using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Common;
using System.Text;
using System.Globalization;
using System.Web.Configuration;
using ResourceBlender.Core;
using ResourceBlender.DAL;
using ResourceBlender.NET;

/// <summary>
/// Shows unused resources in a grid, allowing the user to filter by language and delete
/// </summary>
public partial class UnusedResources : LocalPage
{
    private Database db;
    /// <summary>
    /// Fills the raddio boxes for each language in the database
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack) {
            var langs = ASPNETBLL.GetUniqueLanguages();
            var adaptedLangs = new List<KeyValuePair<string,string>>();
            foreach(var lang in langs) {
                adaptedLangs.Add(new KeyValuePair<string,string>(lang.Key, lang.Value.EnglishName));
            }
            radLanguage.DataSource = adaptedLangs;
            radLanguage.DataValueField = "Key";
            radLanguage.DataTextField = "Value";
            radLanguage.DataBind();
            if(adaptedLangs.Count > 0) {
                radLanguage.SelectedIndex = 0;
            }
            SelectLanguage(null, EventArgs.Empty);
        }
        Page.ClientScript.RegisterClientScriptInclude("json", ResolveUrl("~/js/jquery.json-1.3.min.js"));
        Page.ClientScript.RegisterClientScriptInclude("resourcejs", ResolveUrl("~/js/resources.js"));
        ScriptManager.RegisterStartupScript(this, typeof(Page), "nojs", "$(function(){ $('#" + btnRefresh.ClientID + "').remove(); });", true);
    }

    /// <summary>
    /// Closes the database connection when rendering is done.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Unload(object sender, EventArgs e) {
        if(db != null && db.Connected) {
            db.CloseConnection();
        }
    }

    /// <summary>
    /// Filters unused resources according to language
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void SelectLanguage(object sender, EventArgs e) {
        if(radLanguage.SelectedItem != null) {
            grdFindUnused.DataBind();
        }
    }

    /// <summary>
    /// Shows the number of items on all pages of the GridView
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.ObjectDataSourceStatusEventArgs"/> instance containing the event data.</param>
    protected void dsResources_Selected(object sender, ObjectDataSourceStatusEventArgs e) {
        DataTable dt = e.ReturnValue as DataTable;
        if(dt != null && radLanguage.SelectedItem != null) {
            lblNumUnused.Text = I18nUtils.GetString("UIStrings", "NumUnusedForLang", dt.Rows.Count.ToString(), radLanguage.SelectedItem.Text);
        }
    }

    /// <summary>
    /// Prompts the user to confirm deletion of a resource when the 'Delete' button is clicked
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewCommandEventArgs"/> instance containing the event data.</param>
    protected void grdFindUnused_RowCommand(object sender, GridViewCommandEventArgs e) {
        grdFindUnused.DataBind();
        switch(e.CommandName) {
            case "deleteresource":
                PromptDelete(int.Parse(e.CommandArgument.ToString()));
                break;
        }
    }

    /// <summary>
    /// Changes the page shown in the GridView
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewPageEventArgs"/> instance containing the event data.</param>
    protected void grdFindUnused_PageIndexChanging(object sender, GridViewPageEventArgs e) {
        grdFindUnused.PageIndex = e.NewPageIndex;
        grdFindUnused.DataBind();
    }

    /// <summary>
    /// Handles the Sorting event of the resource grid.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewSortEventArgs"/> instance containing the event data.</param>
    protected void grdFindUnused_Sorting(object sender, GridViewSortEventArgs e) {
        string oldExpression = grdFindUnused.SortExpression,
               newExpression = e.SortExpression;
        if(oldExpression.IndexOf(newExpression) < 0) {
            if(oldExpression.Length > 0) {
                e.SortExpression = newExpression + "," + oldExpression;
            } else {
                e.SortExpression = newExpression;
            }
        } else {
            e.SortExpression = oldExpression;
        }
        grdFindUnused.DataBind();
    }

    #region Deleting
    /// <summary>
    /// Prompts the user to confirm deletion of multiple selected resources
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnDeleteSelected_Click(object sender, EventArgs e) {
        mltMain.ActiveViewIndex = 1;
        try {
            List<int> ids = new List<int>();
            foreach(GridViewRow row in grdFindUnused.Rows) {
                CheckBox chk = row.Cells[2].FindControl("chkSelect") as CheckBox;
                if(chk != null && chk.Checked) {
                    ids.Add(int.Parse((row.Cells[2].FindControl("btnDelete") as ImageButton).CommandArgument));
                }
            }
            if(ids.Count == 0) {
                litConfirmDelete.Text = "<p>" + I18nUtils.GetString("UIStrings", "NoResourcesWereSelected") + "</p>";
                btnOk.Visible = false;
            } else {
                int numAvailableResources = ResourceBlenderDAL.GetResourceAvailability(ids);
                Session["ids"] = ids;
                litConfirmDelete.Text = "<p>" + I18nUtils.GetString("UIStrings", "DeleteUnusedPluralPrompt", ids.Count.ToString(), numAvailableResources.ToString()).Replace("\n", "</p><p>") + "</p>";
            }
        } catch {
            litConfirmDelete.Text = "<p>" + I18nUtils.GetString("Errors", "ErrorLoadingResource") + "</p>";
        }
        btnOk.Text = I18nUtils.GetString("UIStrings", "DeleteResources");
        btnOk.Visible = true;
    }

    /// <summary>
    /// Confirms deletion of a resource and removes it from the database.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnOk_Click(object sender, EventArgs e) {
        db = new Database();
        db.OpenConnection();
        using(Command cmd = db.CreateCommand()) {
            if(ViewState["transid"] is int) {
                ResourceBlenderDAL.DeleteResource((int)ViewState["transid"]);
                ViewState["transid"] = null;
            } else if(Session["ids"] is List<int>) {
                ResourceBlenderDAL.DeleteResources((List<int>)Session["ids"]);
                Session["ids"] = null;
            }
        }
        mltMain.ActiveViewIndex = 0;
        grdFindUnused.DataBind();
    }

    /// <summary>
    /// Prompts to delete a single resource.
    /// </summary>
    /// <param name="resourceId">The resource ID.</param>
    private void PromptDelete(int resourceId) {
        mltMain.ActiveViewIndex = 1;
        try {
            ViewState["transid"] = resourceId;
            int numTranslations = ResourceBlenderDAL.GetResourceAvailability(new int[] { resourceId });
            string translation = ResourceBlenderDAL.GetResource(resourceId).Translations[radLanguage.SelectedValue].Translation;
            litConfirmDelete.Text = "<p>" + I18nUtils.GetString("UIStrings", "DeleteUnusedPrompt", resourceId.ToString(), translation.ToString(), numTranslations.ToString()).Replace("\n", "</p><p>") + "</p>";
            btnOk.Text = I18nUtils.GetString("UIStrings", "DeleteResource");
            btnOk.Visible = true;
        } catch {
            litConfirmDelete.Text = "<p>" + I18nUtils.GetString("Errors", "ErrorLoadingResource") + "</p>";
        }
    }

    /// <summary>
    /// Redirects the user to the 'Unused resources' page.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnCancelDelete_Click(object sender, EventArgs e) {
        mltMain.ActiveViewIndex = 0;
        grdFindUnused.DataBind();
    }
    #endregion
}
